package com.ztao.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.gson.JsonArray;
import com.heima.model.common.apArticle.pojos.ApArticle;
import com.heima.model.common.apArticle.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.ztao.mapper.ApArticleContentMapper;
import com.ztao.mapper.ArticleMapper;
import com.ztao.service.ApArticleContentService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.SneakyThrows;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;

@Service
public class ApArticleContentServiceImpl implements ApArticleContentService {
    @Resource
    private ApArticleContentMapper apArticleContentMapper;
    @Resource
    private Configuration configuration;
    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private FileStorageServiceImpl fileStorageService;
    @Async
    @Override
    @SneakyThrows
    public ResponseResult createStaticUrl(Long articleId) {
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                .eq(ApArticleContent::getArticleId, articleId));
//       文章内容通过freemark生成html
        Template template = configuration.getTemplate("article.ftl");
//        整合

        HashMap<String, Object> map = new HashMap<>();
        map.put("content", JSONArray.parseArray(apArticleContent.getContent()));
        StringWriter out = new StringWriter();
        template.process(map, out);
        InputStream is = new ByteArrayInputStream(out.toString().getBytes());
//        上传html文件到minio里
        String path = fileStorageService.uploadHtmlFile( apArticleContent.getArticleId() + ".html", is);
//        修改静态页面地址 ap_article表 保持staticUrl
        ApArticle apArticle = new ApArticle();
        apArticle.setId(articleId);
        System.out.println("apArticleid========= = " + apArticle.getId());
        apArticle.setStaticUrl(path);
        articleMapper.updateById(apArticle);
        return ResponseResult.okResult(200, "修改成功");

    }
}
